import { PageData } from "../types";
import mitt from "mitt";
let metapage:Record<string, { cached: boolean, fetching: boolean, data: any }> = {}
const emitter = mitt();
const event: Record<string, string> = {
    pageReady: "pageReady",
}

export function setMetaPage(data: PageData): Promise<any> {
    const url = '/meta/page/set';
    return new Promise((resolve, reject) => {
        window.$theia.http
            .post(url, data)
            .then((response: any) => {
                if(!metapage[data.name]){
                    metapage[data.name] = {cached:false, fetching:false, data:{}};
                }
                metapage[data.name].cached = false;
                resolve(response);
            })
            .catch((err: any) => {
                reject(err);
            });
    });
}
export function getMetaPage(name: string): Promise<any> {
    if(!metapage[name]){
        metapage[name] = { cached: false, fetching: false, data: {} };
    }
    if (metapage[name].cached) {
        return new Promise((resolve) => {
            resolve(metapage[name].data);
        });
    }
    if (metapage[name].fetching) {
        return new Promise((resolve) => {
            emitter.on(event.pageReady, () => {
                resolve(metapage[name].data);
            })
            if (metapage[name].cached) {
                resolve(metapage[name].data);
            }
        });
    }
    metapage[name].fetching = true;
    const url = '/meta/page/query';
    return new Promise((resolve, reject) => {
        window.$theia.http
            .post(url, {name:name})
            .then((response: any) => {
                metapage[name].cached = true;
                metapage[name].fetching = false;
                metapage[name].data = response;
                emitter.emit(event.pageReady);
                resolve(response);
            })
            .catch((err: any) => {
                metapage[name].fetching = false;
                reject(err);
            });
    });
}